<?php


	include_once("cmsConfig.php");
	include_once("CmsStatusMessage.php");


	class CmsFormImport {

		var $formId;
		var $authInfo;
		var $db;
		var $debugMode;
		var $addMetaLabelToDocument;
		var $useMetadataLookUp = true;

		var $formDescription;
		var $formElements;
		var $availableFields = array();
		var $availableLabels = array();

		
		var $gid;
		
		
		function CmsFormImport( $formId, &$authInfo, &$db, $debugMode=0, $addMetaLabelToDocument=0, $useMetadataLookUp=true) {
			$this->formId = $formId;
			$this->authInfo  = $authInfo;
			$this->db = &$db;
			$this->debugMode = $debugMode;
			$this->addMetaLabelToDocument = $addMetaLabelToDocument;
			$this->useMetadataLookUp = $useMetadataLookUp;
			
			$cmsTableWriter = new CmsTableWriter(CMS_FORM_DESC_FORMAT, $db);
			$this->formDescription = $cmsTableWriter->readItem($this->formId);
			$this->formElements = new CmsFormElement($this->formDescription, $db);
			$this->gid = $this->formDescription->gid;
			
			unset($this->formDescription->formid);
			unset($this->formDescription->formname);
			unset($this->formDescription->usertype);
			unset($this->formDescription->editmode);
			unset($this->formDescription->uid);
			unset($this->formDescription->gid);
			unset($this->formDescription->permission);
			unset($this->formDescription->sidebarmodule);
			unset($this->formDescription->activemodule);
			unset($this->formDescription->contentmodule);
			unset($this->formDescription->modeaccess);
			unset($this->formDescription->displaygroup);
			
			unset($this->formDescription->documenttypecode);
//			unset($this->formDescription->categorycode);
			unset($this->formDescription->datelogged);
			unset($this->formDescription->documentdate);
			unset($this->formDescription->documentyear);
			unset($this->formDescription->startdate);
			unset($this->formDescription->enddate);
			//unset($this->formDescription->documentcode);			

			
			foreach($this->formDescription as $field=>$v){
				if($v)
					array_push($this->availableFields, $field);
			}
			
			// label of available fields
			foreach($this->availableFields as $field){
				$e = $this->formElements->getElementDescriptor($this->formDescription->$field);
				array_push($this->availableLabels,$e->label);
			}			


		}
		
		function processImport() {
			
//			echo $this->useMetadataLookUp ? "T":"F";
			
			$cmsStatusMessage = new CmsStatusMessage();
			
			$csvFile = extractArrayWithKeyFromArray("csvFile", $_FILES);
			
			// validate the file
			if(!key_exists('csvFile', $_FILES) || !key_exists('tmp_name', $csvFile) || !is_uploaded_file($csvFile['tmp_name']) ){
				$cmsStatusMessage->addValidationMessageForKey('Content','f_FILE_NOT_FOUND',CMS_STATUS_ERROR); //File not found.
				return $cmsStatusMessage;
			}
			
// we remove this test here as we dont always get the correct mime type..
//			if(extractStringWithKeyFromArray("type", $csvFile)!='text/csv' && extractStringWithKeyFromArray("type", $csvFile)!='application/vnd.ms-excel'){
//				$cmsStatusMessage->addValidationMessageForKey('Content','f_NOT_CSV_FILE',CMS_STATUS_ERROR); //Not a CSV file.
//				return $cmsStatusMessage;
//			}			
			// more validation here?
			
			
			
			
			// allow meta data to import
			$cmsMetaDataFieldsMapping = array('Label:'=>'metadata_label', 'Rank:'=>'metadata_rank');
			
			// fields mapping ---> move to constructor 
			$cmsFieldsMapping = array();
			$cmsFieldsType = array();
			foreach($this->availableFields as $field){
				// we need to know the actual 'field name' and 'element type' from each 'element label'
				$e = $this->formElements->getElementDescriptor($this->formDescription->$field);
				$cmsFieldsMapping[$e->label] = $field;	// Active?: => active
				$cmsFieldsType[$e->label] = $e->elementtype;	// Active?: => 4
					
			}			
			
			
			
			// finally begin to do the job !!!!
			$documentType = getDocumentTypeCodeFromFormId($this->formId, $this->db);
			

			
			$csvFilePath = $csvFile['tmp_name'];
			$cvsMetaDataFieldsMapping = array();
			$cvsFieldsMapping = array();
			$cvsFieldsType = array();
			
			$row = 0;
			$handle = fopen($csvFilePath, "r");//
			while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
						
			    $num = count($data);
			    if($this->debugMode==1 && $row==0)
				    echo "There are $num fields in the file:<br /><br />\n";
					
			    $row++;
			    if($row==1){
				for ($c=0; $c < $num; $c++) {
					
					if(key_exists($data[$c],$cmsMetaDataFieldsMapping))
						$cvsMetaDataFieldsMapping[$c] = $cmsMetaDataFieldsMapping[$data[$c]];
					
					if(key_exists($data[$c],$cmsFieldsMapping)){
						$cvsFieldsMapping[$c] = $cmsFieldsMapping[$data[$c]]; // $data[$c] = $e->label
						$cvsFieldsType[$c] = $cmsFieldsType[$data[$c]];
					}
					
					if($this->debugMode==1)
						echo $data[$c].'    &nbsp;&nbsp;&nbsp;   ';
				}
				if($this->debugMode==1)
					echo '<br /><br />';
				continue;
			    }
				    
			    
			    $dataToSave = array();
			    $_REQUEST = array();
			    $metaDataToSave = array();
			    $dataToSave['documenttypecode'] = $documentType;
			    $dataToSave['gid'] = $this->gid;
					
			    if($this->debugMode==1)
				    echo 'Import Line: '.$row."<br />";	
						    
			    for ($c=0; $c < $num; $c++) {
					if($this->debugMode==1)
						echo $data[$c] . '    &nbsp;&nbsp;&nbsp;   ';
					
				if (key_exists($c,$cvsMetaDataFieldsMapping)){
					
					$_REQUEST[$cvsMetaDataFieldsMapping[$c]] = $data[$c];
					
				} else if (!key_exists($c,$cvsFieldsType)){
					
					continue;
				 	
				} else if ( $this->useMetadataLookUp && $cvsFieldsType[$c]==CMS_ELEMENT_DROPDOWN){
						
					$metadatalabel = $data[$c];
					$query = "SELECT c.documentcode FROM cmscontentmetadata cmd, content c WHERE cmd.label='$metadatalabel' AND cmd.documentcode=c.documentcode";
					$this->db->executeQuery($query);
					$document = $this->db->nextObject();
					
					if($document)
						$dataToSave[$cvsFieldsMapping[$c]] = $document->documentcode;	
						
				} else if($cvsFieldsType[$c]==CMS_ELEMENT_CHECKBOX_LIST){
						
					$metadatalabelList = explode(';', $data[$c]);
					$manyTomany = array();
					foreach($metadatalabelList as $metadatalabel){
						
						if ($this->useMetadataLookUp) {
							$query = "SELECT c.documentcode FROM cmscontentmetadata cmd, content c WHERE cmd.label='$metadatalabel' AND cmd.documentcode=c.documentcode";
							$this->db->executeQuery($query);
							$document = $this->db->nextObject();
	
							if($document)
								array_push($manyTomany, $document->documentcode);
													
						} else {
							array_push($manyTomany, $metadatalabel);

						}
						

						
					}
			
					$dataToSave[$cvsFieldsMapping[$c]] = $manyTomany;
			
				} else {
					
					$dataToSave[$cvsFieldsMapping[$c]] = $data[$c];
					
				}
				

			    }
			    if($this->debugMode==1)
				echo '<br /><br />';
			
			
			
			
			    $documentcode = (isset($dataToSave['documentcode']) && $dataToSave['documentcode']>0)?$dataToSave['documentcode']:null;
			    
			    
			    if(!isset($_REQUEST['metadata_label']) && $this->addMetaLabelToDocument==1 && isset($dataToSave['title'])){
				    
			    	$_REQUEST['metadata_label'] = $this->setUniqueMetaDataLabelFromTitle($dataToSave['title'],$documentcode);	
			    }	
			
			
				    
			    if($this->debugMode==1){
				    myPrintR($dataToSave);
				    myPrintR($_REQUEST);
			    }else{

				    include_once("lib/CmsWriter.php");
				    $cmsWriter = new CmsWriter( $this->formId, $documentcode, &$dataToSave, &$this->authInfo, &$this->db);
				    $message = $cmsWriter->processFormData();
								
				    if($message->hasErrors){
					print '<span style="color:red">';
					myPrintR($message);
					print '</span>';
				    }else{
						    
					print '<span style="color:blue">';
					myPrintR($dataToSave);
					myPrintR($_REQUEST);
					print '</span>';
				    }
				    
			    }
					    
			}
			fclose($handle);			

			return $cmsStatusMessage;
		}
		
		function setUniqueMetaDataLabelFromTitle($title,$documentcode){
			
			$search = array(
				' & ',
				'&',
				'/',
				' '
				);
			$replace = array(
				'-and-',
				'-and-',
				'-',
				'-'
				);
			
			$label = strtolower(preg_replace('/[^\d\w\-]/', '', str_replace($search,$replace,$title)));
			
		
			$currentLabel = $label;
			

			$query = "SELECT label FROM cmscontentmetadata WHERE label='$currentLabel'";
			if(!is_null($documentcode))	$query .= " AND documentcode!='$documentcode'";
			$query .= " LIMIT 1";
			$this->db->executeQuery($query);
			while($document = $this->db->nextObject()){
				
			
				if(!isset($c)){
					$c = 1;
					$currentLabel = $label."-$c";
				}else{
					$c++;
					$currentLabel = $label."-$c";
				}
				
				$query = "SELECT label FROM cmscontentmetadata WHERE label='$currentLabel'";
				if(!is_null($documentcode))	$query .= " AND documentcode!='$documentcode'";
				$query .= " LIMIT 1";				
				$this->db->executeQuery($query);
			
			}
			
			
			return $currentLabel;
		
		}
		
		
	}
?>	
